﻿using System;
using System.Windows.Controls;
using Microsoft.Practices.Composite.Events;
using StockholmsStad.Windows.UI.Modules.Maintenance.Interfaces;
using System.Collections.Generic;
using StockholmsStad.Windows.UI.Modules.Maintenance.Models;

namespace StockholmsStad.Windows.UI.Modules.Maintenance.Views
{
    /// <summary>
    /// Interaction logic for ScheduleGenerateTimeView.xaml
    /// </summary>
    public partial class ScheduleGenerateTimeView : IScheduleGenerateTimeView
    {
        private readonly IMaintenanceService maintenanceService;
        private readonly GeneratedMonthsView monthsView;
        private readonly List<int> intervals = new List<int> {5, 10, 15, 20};

        public ScheduleGenerateTimeView(IMaintenanceService service)
        {
            maintenanceService = service;
            InitializeComponent();
            Model = new GenerateTimePresentationModel();
            Loaded += ScheduleGenerateTimeView_Loaded;

            cbInterval.ItemsSource = intervals;

            monthsView = new GeneratedMonthsView(service);
            monthsView.SetValue(Grid.ColumnProperty, 1);
            xGrid.Children.Add(monthsView);

            datePickerStart.MinDate = DateTime.Now;
            datePickerEnd.MinDate = DateTime.Now.AddDays(1);
        }

        #region IScheduleGenerateTimeView Members

        public event EventHandler<DataEventArgs<GenerateTimePresentationModel>> TimeGenerated;

        public GenerateTimePresentationModel Model
        {
            get { return DataContext as GenerateTimePresentationModel; }
            set
            {
                var model = value;
                model.Generated += model_Generated;
                model.Cancelled += model_Cancelled;
                DataContext = model;
            }
        }

        void model_Cancelled(object sender, DataEventArgs<GenerateTimePresentationModel> e)
        {
            monthsView.UnloadView();
            //xGrid.InvalidateVisual();
        }

        #endregion

        private void ScheduleGenerateTimeView_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            Model = maintenanceService.RetrieveSchedule();
        }

        private void model_Generated(object sender, DataEventArgs<GenerateTimePresentationModel> e)
        {
            if(e.Value != null)
            {
                TimeGenerated(this, new DataEventArgs<GenerateTimePresentationModel>(e.Value));
            }
        }

        private void CheckBox_Checked(object sender, System.Windows.RoutedEventArgs e)
        {
            datePickerEnd.IsEnabled = cbIncludeAnotherDay.IsChecked.Value ? false : true;
        }
    }
}
